import { reactive } from 'vue';

export const useUpload = (props, emits, inputRef) => {
    const uploadFileData = reactive({
        list: [],
    });
    const handleChange = e => {
        upload(e.target.files);
        inputRef.value.value = null;
    };
    /**
     * @description: 上传多个附件,上传结束将图片加入subCategory
     *                temporary 临时数据
     */
    const upload = files => {
        uploadFileData.list = Array.prototype.slice.call(files);
        if (uploadFileData.list.length === 0) return;
        const before = props.beforeUpload(uploadFileData.list, props.subCategoryItem);
        if (before && before.then) {
            before.then(processedFiles => {
                const { fileList, ...data } = props.subCategoryItem;
                let uploadFiles = processedFiles.map((item, index) => {
                    const _downloadUrl =
                        item.downloadUrl && (item.downloadUrl.indexOf('?') != -1 ? `${item.downloadUrl}&p=downlaod` : `${item.downloadUrl}?p=download`);
                    return {
                        downloadUrl: _downloadUrl,
                        thumbnailUrl: item.thumbnailUrl,
                        fileId: item.path,
                        id: item.path,
                        temporary: true,
                        previewUrl: item.previewUrl,
                        type: item.type,
                        ...data,
                    };
                });
                emits('uploadSuccess', uploadFiles);
            });
        }
    };

    return {
        handleChange,
    };
};